﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Browser;
using SilverQuery;

namespace SilverQueryDemo.jqia
{
	/// <summary>
	/// Custom SilverQuery Plugins for the jQuery in Action BootCloset sample.
	/// </summary>
	public static class BootClosetPlugins
	{
		/// <summary>
		/// termifier plugin used by the jQuery in Action BootClost sample.
		/// </summary>
		public static jQuery termifier(this jQuery @this, map options)
		{
			return new termifierPlugin().Execute(@this, options);
		}

		/// <summary>
		/// Empty all the options from a select element.
		/// </summary>
		/// <param name="this"></param>
		/// <returns></returns>
		public static jQuery emptySelect(this jQuery @this)
		{
			return new emptySelectPlugin().Execute(@this);
		}

		/// <summary>
		/// Load a select element with options.
		/// </summary>
		public static jQuery loadSelect(this jQuery @this, IEnumerable<SelectOption> options)
		{
			return new loadSelectPlugin().Execute(@this, options);
		}

		private class emptySelectPlugin : SilverQueryPlugin
		{
			public override jQuery Execute(jQuery set)
			{
				return set.each((index, elem) =>
				{
					@q(elem).children("option").remove();
				});
			}
		}

		/// <summary>
		/// Implementation of the termifier plugin.
		/// </summary>
		private class termifierPlugin : SilverQueryPlugin
		{
			public override jQuery Execute(jQuery set, map options)
			{
				options = Utility.extend(new map() { 
					{ "lookupResource", "getTerm.aspx" }, 
					{ "flyoutClass", "lookerUpperFlyout" } 
				}, options ?? new map());

				set.attr("title", "Click me for my definition!");

				return set.click(e =>
				{
					Ajax.get(
						String.Format((string)options["lookupResource"], @q(e.currentTarget).html()),
						null,
						(response, error) =>
						{
							var termtip = @q("<div />");
							termtip.css(new map(){
								{"position", "absolute"}, 
								{"left", e.pageX }, 
								{"top", e.pageY}, 
								{"cursor", "pointer"},
								{"display", "none"}});
							termtip.html(response).addClass((string)options["flyoutClass"]);
							termtip.click(e1 =>
							{
								@q(e1.target).fadeOut(500, () => { @q(e1.target).remove(); });
								return false;
							});
							termtip.appendTo("body").fadeIn("normal");
						});

					return false;
				});
			}
		}

		private class loadSelectPlugin : SilverQueryPlugin
		{
			public override jQuery Execute(jQuery set, params object[] args)
			{
				var options = (IEnumerable<SelectOption>)args[0];
				return set.emptySelect().each((index, elem) =>
				{
					var current = @q(elem);
					if (current.isMatch("select"))
					{
						foreach (var option in options)
						{
							current.append(@q("<option />").attr("value", option.Value).text(option.Caption));
						}
					}
				});
			} 
		}
	}
}
